//
//  RegexHelper.swift
//  Sevengrass
//
//  Created by Kipp Dev on 2017/12/16.
//  Copyright © 2017年 Syrena. All rights reserved.
//

import Foundation

// MARK: - 正则表达式的枚举
enum RegexType: String {
    case email = "^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
    case fixedTelephone = "^(0[0-9]{2})\\d{8}$|^(0[0-9]{3}(\\d{7,8}))$"
    case phone = "^1(3[0-9]|5[0-9]|7[0-9]|8[0-9]|4[0-9]|9[0-9])\\d{8}$"
    case username = "^[a-z0-9_-]{3,16}$" //用户名验证，3-16个字符
    case password = "^[a-z0-9_-]{6,18}$" //匹配密码的格式，6-18个字符
    case url = "^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$" //匹配一个链接是否正常
    case price = "^[0-9]+(.[0-9]{2})?$"
    case number = "^[0-9]*$"
}

/// 正则表达式工具
struct RegexHelper {
    let regex: NSRegularExpression
    init(_ pattern: String) throws {
        try regex = NSRegularExpression(pattern: pattern, options: .caseInsensitive)
    }

    func match(_ input: String) -> Bool {
        let matches = regex.matches(in: input, options: [], range: NSRange.init(location: 0, length: input.utf16.count))
        return !matches.isEmpty
    }
}

precedencegroup MatchPrecedence {
    associativity: none
    higherThan: DefaultPrecedence
}

// MARK: - 自定义一个操作符，用于正则表达式的判断
infix operator =~: MatchPrecedence

/// 正则表达操作符
///
/// - Parameters:
///   - lhs: 左边填需要判断的值
///   - rhs: 右边填正则枚举
/// - Returns: 返回 Bool
func =~ (lhs: String, rhs: RegexType) -> Bool {
    do {
        return try RegexHelper(rhs.rawValue).match(lhs)
    } catch _ {
        return false
    }
}
